package com.znsb.msfq.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.znsb.msfq.R;
import com.znsb.msfq.app.ZnsbApp;
import com.znsb.msfq.bean.BannerBean;
import com.znsb.msfq.bean.Bean;
import com.znsb.msfq.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @name：
 * @author： 孙科技
 * @phone： 13308334117
 * @createTime： 2017/2/8
 * @modifyTime： 2017/2/8
 * @explain：网络请求
 */

public class HttpUtils {
    private static HttpUtils httpUtils = null;
    private static OkHttpClient mOkHttpClient = null;
    private static Activity context;

    public HttpUtils(Activity context) {
        this.context = context;
    }

    public static HttpUtils getInstance(Activity context) {
        if (null == httpUtils) {
            httpUtils = new HttpUtils(context);
            initOkHttpClient();
        }
        return httpUtils;
    }

    private static void initOkHttpClient() {
        File sdcache = context.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        mOkHttpClient = builder.build();
    }

    /**
     * okhttp get请求
     */
    public Call getRequest(String url) {
        //2. 获取Request对象
        Request request = new Request.Builder()
                .url(url)
                .build();
        //3. 获取Call对象
        Call call = mOkHttpClient.newCall(request);
        //4. 获取Response对象, 通过接口回调方式返回Response
        return call;
    }

    /**
     * okhttp post请求
     */
    public void postRequest(String url, Map<String, String> maps, final ResponseUtils responses) {

        FormBody.Builder builder = new FormBody.Builder();
        if (maps != null) {
            for (String key : maps.keySet()) {
                builder.add(key, maps.get(key));
            }
        }
        final Request.Builder request = new Request.Builder();
        request.url(url);
        if (!ValidateUtils.isNullOrEmpty(SPUtils.getCookie())) {
            request.addHeader("Cookie", SPUtils.getCookie());
        }
        request.post(builder.build());
        Call call = mOkHttpClient.newCall(request.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.TextToast(ZnsbApp.mContext, "网络请求失败", 2000);
                responses.onFailure("失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                for (String str : cookies) {
                    if (str.startsWith("SESSION")) {
                        //将sessionId保存到本地
                        if (ValidateUtils.isNullOrEmpty(SPUtils.getCookie()))
                            SPUtils.saveToApp(ConfigUtils.INFO_COOKIES, str.split(";")[0]);
                    }
                }
                String result = response.body().string();
                String code = JsonResult.resultCodes(result);
                LogUtils.i("", ">>>>>>result" + result);
                if (code.equals("C0001")) {
                    responses.onSucceed(code, JsonResult.resultResponse(result));
                } else if (JsonResult.resultCodes(result).equals("C0003")) {
                    //用户登陆超时或别处登录时清空用户个人资料及登录状态
                    SPUtils.remove(ZnsbApp.mContext, SPUtils.APP_COMMON_FILE_NAME);
                    ToastUtils.TextToast(ZnsbApp.mContext, ZnsbApp.mContext.getResources().getString(R.string.elsewherelogin), 3000);
                    responses.onSucceed(code, null);
                } else {
                    responses.onSucceed(code, null);
                    ToastUtils.TextToast(ZnsbApp.mContext, ZnsbApp.mContext.getResources().getString(R.string.networkerrors), 3000);
                }
            }
        });
    }

    /**
     * okhttp post请求
     */
    public void postAsnyRequest(final String url, Map<String, Object> maps, final ResponseUtils responses) {
        FormBody.Builder builder = new FormBody.Builder();
        if (maps != null) {
            for (String key : maps.keySet()) {
                builder.add(key, String.valueOf(maps.get(key)));
            }
        }
        final Request.Builder request = new Request.Builder();
        request.url(url);
        if (!ValidateUtils.isNullOrEmpty(SPUtils.getCookie())) {
            request.addHeader("Cookie", SPUtils.getCookie());
        }
        request.post(builder.build());
        LogUtils.i("TAG:", "url=" + url + "?param=" + maps.toString());
        Call call = mOkHttpClient.newCall(request.build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.TextToast(ZnsbApp.mContext, "网络请求失败", 2000);
                responses.onFailure("失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                for (String str : cookies) {
                    if (str.startsWith("SESSION")) {
                        //将sessionId保存到本地
                        SPUtils.saveToApp(ConfigUtils.INFO_COOKIES, str.split(";")[0]);
                    }
                }
                String result = response.body().string();
                try {
                    Bean data = (Bean) GsonUtils.getGsonData(Bean.class, result);
                    if (data != null) {
                        if (!ValidateUtils.isNullOrEmpty(data.getResult().getToken())) {
                            SPUtils.saveToApp(ConfigUtils.REQ_TOKEN, data.getResult().getToken());
                        }
                        if (!ValidateUtils.isNullOrEmpty(data.getResult().getCookie())) {
                            SPUtils.saveToApp(ConfigUtils.REQ_TOKEN, data.getResult().getCookie());
                        }
                        JSONObject request = null;
                        try {
                            request = JsonResult.resultResponse(result);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!ValidateUtils.isNullOrEmpty(request))
                            if (ErrorCodeUtils.code1.equals(data.getResult().getCode()) || ErrorCodeUtils.code6.equals(data.getResult().getCode())) {
                                responses.onSucceed(data.getResult().getCode(), request);
                            } else {
                                if (!url.equals(UrlUtils.MSFQ_URL_LOGINOUT))
                                    ToastUtils.TextToast(ZnsbApp.mContext, ErrorCodeUtils.getCode(data.getResult().getCode()), 2000);
                            }
                    }

                } catch (Exception e) {

                }
            }
        });
    }
//
//    private static Dialog dialog = null;
//    private static View view = null;
//
//    public static Dialog createLoadingDialog(String msg) {
//        if (dialog == null) {
//            dialog = new Dialog(context, R.style.loading);
//            view = LayoutInflater.from(context).inflate(R.layout.loading, null);
//        }
//        dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
//        TextView content = (TextView) view
//                .findViewById(R.id.loading_tv);
//        content.setText(msg);
//        ImageView loading = (ImageView) view
//                .findViewById(R.id.loading_img);
//        AnimationDrawable animationDrawable = (AnimationDrawable) loading.getDrawable();
//        animationDrawable.start();
//        dialog.setContentView(view);
//
//        return dialog;
//    }

    /**
     * 上传文件
     */
    public final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");

    private void postAsynFile(String url, String imgPath, Map<String, Object> maps) {
        File file = new File(imgPath);
        final Request.Builder request = new Request.Builder();
        request.url(url);
        if (!ValidateUtils.isNullOrEmpty(SPUtils.getCookie())) {
            request.addHeader("Cookie", SPUtils.getCookie());
        }
        request.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file));
        LogUtils.i("TAG:", "url=" + url + "?param=" + maps.toString());

        mOkHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            }
        });
    }

    /**
     * 下载文件
     */
    private void downAsynFile() {
        String url = "http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream inputStream = response.body().byteStream();
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(new File("/sdcard/wangshu.jpg"));
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    fileOutputStream.flush();
                } catch (IOException e) {
                    LogUtils.i("wangshu", "IOException");
                    e.printStackTrace();
                }

                LogUtils.i("wangshu", "文件下载成功");
            }
        });
    }

    /**
     * 多文件上传
     */
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static void sendMultipart(String url, Map<String, Object> maps, List<File> files, final ResponseUtils responses) {
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);
        //遍历map中所有参数到builder
        if (maps != null) {
            for (String key : maps.keySet()) {
                multipartBodyBuilder.addFormDataPart(key, String.valueOf(maps.get(key)));
            }
        }
        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files != null) {
            for (File file : files) {
                multipartBodyBuilder.addFormDataPart("uploadFile" + file.length(), file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
        }
        final Request.Builder request = new Request.Builder();
        request.url(url);
        if (!ValidateUtils.isNullOrEmpty(SPUtils.getCookie())) {
            request.addHeader("Cookie", SPUtils.getCookie());
        }
        request.post(multipartBodyBuilder.build());
        LogUtils.i("TAG:", "url=" + url + "?param=" + maps.toString() + "?file=" + files.toString());
        mOkHttpClient.newCall(request.build()).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                ToastUtils.TextToast(ZnsbApp.mContext, "上传图片失败!", 2000);
                responses.onFailure("失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                for (String str : cookies) {
                    if (str.startsWith("SESSION")) {
                        //将sessionId保存到本地
                        SPUtils.saveToApp(ConfigUtils.INFO_COOKIES, str.split(";")[0]);
                    }
                }
                String result = response.body().string();
                try {
                    Bean data = (Bean) GsonUtils.getGsonData(Bean.class, result);
                    if (data != null) {
                        JSONObject request = null;
                        try {
                            request = JsonResult.resultResponse(result);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (!ValidateUtils.isNullOrEmpty(request))
                            if (ErrorCodeUtils.code1.equals(data.getResult().getCode())) {
                                responses.onSucceed(data.getResult().getMsg(), request);
                            } else {
                                ToastUtils.TextToast(ZnsbApp.mContext, ErrorCodeUtils.getCode(data.getResult().getCode()), 2000);
                            }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    /**
     * 登录前请求参数处理
     *
     * @param maps
     * @return
     */
    public static Map<String, Object> getMaps(Map<String, Object> maps) {
        Map<String, Object> map = new HashMap<>();
        map.put("header", OverallData.header);
        JSONObject param = new JSONObject();
        try {
            if (maps != null) {
                for (String key : maps.keySet()) {
                    param.put(key, maps.get(key));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        map.put("param", param.toString());
        return map;
    }

    /**
     * 登陆后请求参数处理
     *
     * @param maps
     * @return
     */
    public static Map<String, Object> getLoginMaps(Map<String, Object> maps) {
        Map<String, Object> map = new HashMap<>();
        JSONObject params = new JSONObject();
        try {
            params.put("reqKey", OverallData.reqKey);
            params.put("token", SPUtils.getToken());
            params.put("cookie", SPUtils.getCookie());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("header", params.toString());
        JSONObject param = new JSONObject();
        try {
            if (maps != null) {
                for (String key : maps.keySet()) {
                    param.put(key, maps.get(key));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        map.put("param", param.toString());
        return map;
    }
}
